package cn.qidisoft.edu.hzjt.controller.zyc;

import cn.qidisoft.core.common.log.LoggerAdapter;
import cn.qidisoft.core.common.log.LoggerAdapterFactory;
import cn.qidisoft.core.common.pagination.Page;
import cn.qidisoft.core.common.pagination.PaginationBean;
import cn.qidisoft.core.util.moffice.excel.ExpExcelUtil;
import cn.qidisoft.core.web.customargument.bind.annotation.IfNeedLogin;
import cn.qidisoft.core.web.customargument.bind.annotation.Token;
import cn.qidisoft.edu.hzjt.controller.BaseController;
import cn.qidisoft.edu.hzjt.exception.RPCException;
import cn.qidisoft.edu.hzjt.model.Employee;
import cn.qidisoft.edu.hzjt.model.ResponseResult;
import cn.qidisoft.edu.hzjt.model.Student;
import cn.qidisoft.edu.hzjt.model.zyc.PartyBranch;
import cn.qidisoft.edu.hzjt.model.zyc.PartyLeagueMember;
import cn.qidisoft.edu.hzjt.service.zyc.IDyService;
import cn.qidisoft.edu.hzjt.service.zyc.IDzbService;
import cn.qidisoft.edu.hzjt.service.zyc.IEmpService;
import cn.qidisoft.edu.hzjt.service.zyc.IStudentService;
import cn.qidisoft.edu.hzjt.utils.LogType;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 党员管理
 * 
 * @author zhangwenliang
 * @date 2018.11.16
 */
@Controller
@RequestMapping(value = "/dy/")
@IfNeedLogin(needLogin = true)
public class DyController {
	protected static final LoggerAdapter LOGGER = LoggerAdapterFactory.getLogger(LogType.HZJT_LOGGER.val);
	@Autowired
	private IDyService dyService;

	@Autowired
	private IDzbService dzbService;

	@Autowired
	private IEmpService empService;

	@Autowired
	private IStudentService studentService;

	/**
	 * 跳转到党员管理列表页面
	 * 
	 * @return
	 */
	@RequestMapping(value = "list")
	public String list(ModelMap model, HttpServletRequest request) {
		// 获取党支部信息
		PartyBranch partyBranch = new PartyBranch();
		List<PartyBranch> pList = (List<PartyBranch>) dzbService.getAllDzbinfo(partyBranch);
		request.setAttribute("pList", pList);
		return "zyc/dy/list";
	}

	/**
	 * 获取列表分页数据
	 * 
	 * @param model
	 * @param request
	 * @param pageSize
	 * @param currentPage
	 * @param partyBranch
	 * @return
	 */
	@RequestMapping("getListData")
	@ResponseBody
	public ResponseResult getListData(ModelMap model, HttpServletRequest request,
			@RequestParam(value = "rows", required = false) String pageSize,
			@RequestParam(value = "page", required = false) String currentPage, PartyLeagueMember PartyLeagueMember) {
		System.out.println(pageSize + currentPage);
		Page page = new Page();
		page.setCurrPage(currentPage == null ? 0 : Integer.valueOf(currentPage));
		page.setPageSize(pageSize == null ? 10 : Integer.valueOf(pageSize));
		BaseController.setSortByColumn(request, "rDRQ", "desc");
		PartyLeagueMember.setOrderField((String) request.getAttribute("orderField"));
		PartyLeagueMember.setOrderFlag((String) request.getAttribute("orderFlag"));
		Map<String, Object> queryMap = new HashMap<String, Object>();
		String begintime = request.getParameter("begintime");
		String endtime = request.getParameter("endtime");
		queryMap.put("PartyLeagueMember", PartyLeagueMember);
		queryMap.put("begintime", begintime);
		queryMap.put("endtime", endtime);
		PaginationBean<PartyLeagueMember> paginationBean = dyService.getListData(queryMap, page);
		ResponseResult result = new ResponseResult();
		result.setTotal(paginationBean.getTotalRecords());
		result.setRows(paginationBean.getPageList());
		return result;
	}
	/**
	 * 跳转到添加页面
	 * 
	 * @param model
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "add")
	@Token(save = true)
	public String add(ModelMap model, HttpServletRequest request) {
		try {
			PartyBranch partyBranch = new PartyBranch();
			List<PartyBranch> pList = (List<PartyBranch>) dzbService.getAllDzbinfo(partyBranch);
			List<Employee> employees = empService.getDmplist();
			request.setAttribute("partyBranch", pList);
			request.setAttribute("employees", employees);
			List<Student> pStudents = studentService.queryAllStu();
			request.setAttribute("student", pStudents);
			return "zyc/dy/add";
		} catch (Exception e) {
			LOGGER.error("获得xxxxx信息 addStudentDemoForward [{}] error," + this.getClass().getName() + "=[{}]",
					this.getClass().getName(), e.getMessage());
			return "error/error";
		}
	}

	/**
	 * 添加党员信息
	 * 
	 * @param model
	 * @param request
	 * @param pM
	 * @return
	 */
	@RequestMapping(value = "insert", method = RequestMethod.POST)
	public String insert(ModelMap model, HttpServletRequest request, PartyLeagueMember pM) {
		try {
			List<PartyLeagueMember> pList = new ArrayList<>();
			pM.setgID("");
			if(null == pM.getEmpId()) {
				pM.setEmpId(0);				
			}
			if (null == pM.getdYLDQK()) {
				pM.setdYLDQK("0");
			}
			if (null == pM.getzZDYQK()) {
				pM.setzZDYQK("0");
			}
			pM.setStuId(0);
			pList.add(pM);
			// 插入党员
			dzbService.insertDyb(pList);
			request.setAttribute("partyLeagueMember", pM);
			String action = request.getParameter("action");
			if (action.equals("1")) {
				return "redirect:./view?dYID=" + pM.getdYID();
			} else if (action.equals("2")) {
				return "redirect:./add";
			}
		} catch (Exception e) {
			e.printStackTrace();
			LOGGER.error("获得xxxxx信息 addStudentDemo [{}] error," + this.getClass().getName() + "=[{}]",
					this.getClass().getName(), e.getMessage());
			return "error/error";
		}
		return null;
	}
	/**
	 * 跳转到浏览页面
	 * 
	 * @param request
	 * @return
	 */
	@RequestMapping("view")
	public String view(HttpServletRequest request) {
		String dYID = request.getParameter("dYID");
		// 获取党员信息(根据党员部id)
		LOGGER.info("dYIDdYIDdYIDdYIDdYIDdYIDdYID+++" + dYID);
		PartyLeagueMember pLeagueMember = dyService.getDybById(Integer.parseInt(dYID));
		if(null !=pLeagueMember.getcSRQ()) {
			pLeagueMember.setcSRQ(pLeagueMember.getcSRQ().substring(0, 19));
		}
		if(null !=pLeagueMember.getrDRQ()) {
			pLeagueMember.setrDRQ(pLeagueMember.getrDRQ().substring(0, 19));
		}
		if(null !=pLeagueMember.getzZRQ()) {
			pLeagueMember.setzZRQ(pLeagueMember.getzZRQ().substring(0, 19));
		}
		if(null !=pLeagueMember.getcJGZSJ()) {
			pLeagueMember.setcJGZSJ(pLeagueMember.getcJGZSJ().substring(0, 19));
		}
		if(null !=pLeagueMember.getjRDZBRQ()) {
			pLeagueMember.setjRDZBRQ(pLeagueMember.getjRDZBRQ().substring(0, 19));
		}
		if(pLeagueMember.getdYLB().equals("1")) {
			pLeagueMember.setdYLB("正式党员");
		} else if(pLeagueMember.getdYLB().equals("2")) {
			pLeagueMember.setdYLB("预备党员");
		}
		if(pLeagueMember.getdJZT().equals("1")) {
			pLeagueMember.setdJZT("正常");
		} else if(pLeagueMember.getdJZT().equals("0")) {
			pLeagueMember.setdJZT("停止党籍");
		}
		if(pLeagueMember.getIsStu().equals("0")) {
			pLeagueMember.setIsStu("否");
		} else {
			pLeagueMember.setIsStu("是");
		}
		if(pLeagueMember.getdYLDQK().equals("0")) {
			pLeagueMember.setdYLDQK("否");
		} else {
			pLeagueMember.setdYLDQK("是");
		}
		if(pLeagueMember.getzZDYQK().equals("0")) {
			pLeagueMember.setzZDYQK("否");
		} else {
			pLeagueMember.setzZDYQK("是");
		}

		request.setAttribute("partyLeagueMember", pLeagueMember);
		return "zyc/dy/view";
	}
	
	/**
	 * 获取党支部名称 党支部书记 党支部委员
	 * 
	 * @param request
	 * @return
	 */
	@RequestMapping("validation")
	@ResponseBody
	public PartyLeagueMember validation(HttpServletRequest request) {
		String xM = request.getParameter("xM");
		PartyLeagueMember pMember = new PartyLeagueMember();
		pMember.setxM(xM);
		// 查询党员
		PartyLeagueMember partyLeagueMember = dyService.selectXm(pMember);
		if(null != partyLeagueMember) {
			return partyLeagueMember;			
		}
		PartyLeagueMember partyLeagueMember2 = new PartyLeagueMember();
		return partyLeagueMember2;
	}

	/**
	 * 跳转到修改页面
	 * 
	 * @param model
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "edit")
	public String edit(ModelMap model, HttpServletRequest request) {
		try {
			String id = request.getParameter("id");
			// 获取党员信息(根据党员部id)
			PartyLeagueMember pLeagueMember = dyService.getDybById(Integer.parseInt(id));
			if(null !=pLeagueMember.getcSRQ()) {
				pLeagueMember.setcSRQ(pLeagueMember.getcSRQ().substring(0, 19));
			}
			if(null !=pLeagueMember.getrDRQ()) {
				pLeagueMember.setrDRQ(pLeagueMember.getrDRQ().substring(0, 19));
			}
			if(null !=pLeagueMember.getzZRQ()) {
				pLeagueMember.setzZRQ(pLeagueMember.getzZRQ().substring(0, 19));
			}
			if(null !=pLeagueMember.getcJGZSJ()) {
				pLeagueMember.setcJGZSJ(pLeagueMember.getcJGZSJ().substring(0, 19));
			}
			if(null !=pLeagueMember.getjRDZBRQ()) {
				pLeagueMember.setjRDZBRQ(pLeagueMember.getjRDZBRQ().substring(0, 19));
			}
			request.setAttribute("PartyLeagueMember", pLeagueMember);
			// 获取党支部信息
			PartyBranch partyBranch = new PartyBranch();
			List<PartyBranch> pList = (List<PartyBranch>) dzbService.getAllDzbinfo(partyBranch);
			request.setAttribute("partyBranch", pList);  
			// 获取职工信息
			List<Employee> employees = empService.getDmplist();
			request.setAttribute("employees", employees);
			// 获取学生信息
			List<Student> pStudents = studentService.queryAllStu();
			request.setAttribute("student", pStudents);
			return "zyc/dy/edit";
		} catch (Exception e) {
			LOGGER.error("获得xxxxx信息 addStudentDemoForward [{}] error," + this.getClass().getName() + "=[{}]",
					this.getClass().getName(), e.getMessage());
			return "error/error";
		}
	}

	/**
	 * 更新党员部信息
	 * 
	 * @param model
	 * @param request
	 * @return 3）保存时，对党支部书记和委员，判断是否在党员信息中，没有，则自动加入党员表
	 */
	@RequestMapping(value = "update")
	public String update(HttpServletRequest request, PartyLeagueMember partyLeagueMember) {
		try {
			partyLeagueMember.setgID("");
			if(null == partyLeagueMember.getEmpId()) {
				partyLeagueMember.setEmpId(0);				
			}
			// 更新党员表
			LOGGER.info("dYIDdYIDdYIDdYIDdYIDdYIDdYID+++" + partyLeagueMember.getdYID());
			if (dyService.updateDybinfo(partyLeagueMember) > 0) {
				request.setAttribute("partyLeagueMember", partyLeagueMember);
				String action = request.getParameter("action");
				if (action.equals("1")) {
					return "redirect:./view?dYID=" + partyLeagueMember.getdYID();
				} else if (action.equals("2")) {
					return "redirect:./add";
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			LOGGER.error("获得xxxxx信息 addStudentDemo [{}] error," + this.getClass().getName() + "=[{}]",
					this.getClass().getName(), e.getMessage());
			return "error/error";
		}
		return null;
	}

	/**
	 * 删除党员信息
	 * 
	 * @param model
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "delete", method = RequestMethod.POST)
	public String delete(ModelMap model, HttpServletRequest request) {
		try {
			String[] idList = request.getParameter("idList").split(",");
			List<Integer> list = new ArrayList<>();
			for (int i = 0; i < idList.length; i++) {
				list.add((Integer.valueOf(idList[i])));

			}
			if (list.size() != 0) {
				dyService.delete(list);
			}
			BaseController.setParameter("msg", "删除成功");
			return "redirect:list";
		} catch (Exception e) {
			e.printStackTrace();
			LOGGER.error("删除 delete [{}] error," + this.getClass().getName() + "=[{}]", this.getClass().getName(),
					e.getMessage());
			return "error/error";
		}
	}

	/**
	 * xxxxx下载
	 * 
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "export_dzb")
	public @ResponseBody void export_dzb(HttpServletRequest request, HttpServletResponse response,
			PartyLeagueMember pM2) throws Exception {
		try {
			String begintime = request.getParameter("begintime");
			String endtime = request.getParameter("endtime");
			Map<String, Object> queryMap = new HashMap<String, Object>();
			queryMap.put("begintime", begintime);
			queryMap.put("endtime", endtime);
			PartyLeagueMember pM = new PartyLeagueMember();
			pM.setdZBID(pM2.getdZBID());
			pM.setdYLB(pM2.getdYLB());
			pM.setdJZT(pM2.getdJZT());
			pM.setxB(pM2.getxB());
			pM.setmZ(pM2.getmZ());
			pM.setwHCD(pM2.getwHCD());
			pM.setIsStu(pM2.getIsStu());
			pM.setxM(pM2.getxM());
			queryMap.put("PartyLeagueMember", pM);
			List<PartyLeagueMember> datalist = dyService.getDybList(queryMap);
			String[][] title_name = { { "党员id", "姓名", "工号", "所在党支部", "加入党组织日期", "转正式党员日期", "党员类别", "党籍状态", "身份证号",
					"出生日期", "学历", "民族", "籍贯", "家庭地址", "联系电话" } };
			String[] title_style = { "hwzs_16_bold_25", "hwzs_16_bold_25", "hwzs_16_bold_25", "hwzs_16_bold_25",
					"hwzs_16_bold_25", "hwzs_16_bold_25", "hwzs_16_bold_25", "kt_12_bold_18", "kt_12_bold_18",
					"kt_12_bold_18", "st_12_r_20", "st_12_r_20", "st_12_r_20", "st_12_n_20", "st_12_n_20" };
			String fileName = "党员信息";
			String[] remark = { "" };
			List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
			if (datalist != null && !datalist.isEmpty()) {
				for (PartyLeagueMember res : datalist) {
					Map<String, Object> map = new LinkedHashMap<String, Object>();
					if(null !=res.getcSRQ()) {
						res.setcSRQ(res.getcSRQ().substring(0, 19));
					}
					if(null !=res.getrDRQ()) {
						res.setrDRQ(res.getrDRQ().substring(0, 19));
					}
					if(null !=res.getzZRQ()) {
						res.setzZRQ(res.getzZRQ().substring(0, 19));
					}
					if(res.getdYLB().equals("1")) {
						res.setdYLB("正式党员");
					} else if(res.getdYLB().equals("2")) {
						res.setdYLB("预备党员");
					}
					if(res.getdJZT().equals("1")) {
						res.setdJZT("正常");
					} else if(res.getdJZT().equals("0")) {
						res.setdJZT("停止党籍");
					}
					map.put("dYID", res.getdYID());
					map.put("xM", res.getxM());
					map.put("gH", res.getgH());
					map.put("dZBID", res.getdZBID());
					map.put("rDRQ", res.getrDRQ());
					map.put("zZRQ", res.getzZRQ());
					map.put("dYLB", res.getdYLB());
					map.put("dJZT", res.getdJZT());
					map.put("sFZH", res.getsFZH());
					map.put("cSRQ", res.getcSRQ());
					map.put("wHCD", res.getwHCD());
					map.put("mZ", res.getmZ());
					map.put("jG", res.getjG());
					map.put("jTDZ", res.getjTDZ());
					map.put("lXDH", res.getlXDH());
					list.add(map);
				}
			}
			HSSFWorkbook wb = ExpExcelUtil.getWorkBookExcel(title_name, title_style, 100, remark, fileName, list);
			try {
				String filenameConvert = "党员信息";/* new String(fileName.getBytes("GB2312"), "ISO8859-1"); */
				response.reset();
				response.setContentType("application/vnd.ms-excel;charset=utf-8");
				response.setHeader("Content-Disposition",
						"attachment;filename=" + new String((filenameConvert + ".xls").getBytes(), "iso-8859-1"));
				response.setDateHeader("Expires", 0);
				ServletOutputStream os = response.getOutputStream();
				wb.write(os);
				os.flush();
			} catch (Exception e) {
				System.out.println("网络连接断开，可能用户取消了导出");
			}
		} catch (RPCException e) {
			LOGGER.error("获得xxxxx信息 exportStudentjobList [{}] error," + this.getClass().getName() + "=[{}]",
					this.getClass().getName(), e.getMessage());
		}
	}

	@InitBinder
	public void initBinder(WebDataBinder binder) {
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		dateFormat.setLenient(false);
		binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
	}
}
